package com.yance.fim.cluster.zookeeper;

import com.yance.fim.config.ConfigParam;
import org.I0Itec.zkclient.IZkChildListener;
import org.I0Itec.zkclient.ZkClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 监听启动器
 */
@Component
@Order(value = 1)
public class WatchZK implements CommandLineRunner {

    private static Logger logger = LoggerFactory.getLogger(RegistryZK.class);

    @Autowired
    private ZkClient zkClient;

    @Autowired
    private ConfigParam configParam;

    @Autowired
    private ServerCache serverCache;

    @Override
    public void run(String... args) throws Exception {
        logger.info("-----------------WatchStart Start-up-----------------");
        zkClient.subscribeChildChanges(configParam.getZkRoot(), new IZkChildListener() {
            @Override
            public void handleChildChange(String parentPath, List<String> currentChildren) throws Exception {
                logger.info("Clear and update local cache parentPath=[{}],currentChildren=[{}]", parentPath,currentChildren.toString());
                serverCache.updateCache(currentChildren);
            }
        });
    }
}
